<template>
    <div>
        <el-form :inline="true" :model="condition" class="search-form" label-width="120px">
            <el-row>
                <el-col :span="8">
                    <el-form-item label="作业港口">
                        <select-port v-model="allPortCodes" :name="allPortCodes" :isMultiple = "true"></select-port>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="作业日期起">
                        <el-date-picker v-model="condition['search_GTE_jobTime']" type="date" placeholder="起始日期"
                                        format="yyyy-MM-dd" value-format="yyyy-MM-dd"></el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="作业日期止">
                        <el-date-picker v-model="condition['search_LTE_jobTime']" type="date" placeholder="结束日期"
                                        format="yyyy-MM-dd" value-format="yyyy-MM-dd"></el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label="作业班组">
                        <el-input v-model="condition['search_LIKE_className']"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="作业班次">
                        <el-input v-model="condition['search_LIKE_workShift']"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-button class="ml-120" @click="loadData">查 询</el-button>
                    <el-button @click="handleExport">导出Excel</el-button>
                </el-col>
            </el-row>
        </el-form>

        <el-table :data="list" border stripe max-height="500" show-summary :summary-method="getSummary" class="mt-10">
            <el-table-column fixed="left" label="序号" min-width="55">
                <template slot-scope="scope">
                    <div>{{ scope.row.index }}</div>
                </template>
            </el-table-column>
            <el-table-column prop="portName" label="作业港口"  min-width="120"></el-table-column>
            <el-table-column prop="pieceTime" label="作业日期"  min-width="120">
                <template slot-scope="scope">
                    {{ scope.row.pieceTime | filterDate }}
                </template>
            </el-table-column>
            <el-table-column prop="groupName" label="作业班组"  min-width="120"></el-table-column>
            <el-table-column prop="planType" label="作业类型"  min-width="120">
                <template slot-scope="scope">
                    {{ scope.row.planType | _filterAllJobStatus }}
                </template>
            </el-table-column>
            <el-table-column prop="workShift" label="作业班次"  min-width="120"></el-table-column>
            <el-table-column prop="containerSize" label="箱尺寸"  min-width="120"></el-table-column>
            <el-table-column prop="jobNum" label="作业量"  min-width="120"></el-table-column>
            <el-table-column prop="piece" label="工时"  min-width="100"></el-table-column>
            <el-table-column fixed="right" align="center" label="操作"  width="100">
                <template slot-scope="scope">
                    <el-button size="small" v-if="scope.row.portName!=='小计'&&power('TALLY_PIECE_STAFF')" type="text"
                               @click="handleSee(scope.row)">
                        明细
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-row class="bottom mt-10" type="flex" justify="space-between" v-show="total>0">
            <div class="oper">

            </div>
            <el-pagination class="page" @size-change="size=>pageInfo.iDisplayLength=size"
                           layout="total, sizes, prev, pager, next, jumper"
                           :current-page.sync="pageInfo.pageStart" :page-sizes="pageInfo.pageArr"
                           :page-size="pageInfo.iDisplayLength" :total="total">
            </el-pagination>
        </el-row>
    </div>
</template>

<script>
    import { getClassCountList } from "@/api/balance/balance";
    import selectPort from '@/components/select/selectPort'
    import { newExportExcel } from "@/utils/newExport";
    import { allJobStatus } from "../../../assets/dict";

    export default {
        name: "作业班组统计",
        components: { selectPort },
        data() {
            return {
                total: 0,
                setTotal: 0,
                pageInfo: this.$defalutPage(),
                listLoading: false,
                condition: {
                    search_LIKE_portName: '',
                    search_GTE_jobTime: '',
                    search_LTE_jobTime: '',
                    search_LIKE_className: '',
                },
                list: [],
                created: true,
                allPortCodes: ''
            }
        },
        mounted() {
            const params = JSON.parse(sessionStorage.getItem('classCount'))
            let portList = ""
            if (params != undefined && params != "" && params.search_IN_portCode != "") {
                portList = params.search_IN_portCode.split(',')
            }
            this.allPortCodes = portList
            this.condition = { ...params }
            this.loadData()
        },
        activated() {
            // const params = JSON.parse(sessionStorage.getItem('classCount'))
            // this.condition = { ...params }
            if (!this.created) {
                const params = JSON.parse(sessionStorage.getItem('classCount'))
                this.condition = { ...params }
                this.loadData()
            }
        },
        methods: {
            loadData() {
                this.condition.search_IN_portCode = this.arrayToString(this.allPortCodes)
                let params = this.$assist.copySearchConditions(this.condition)
                params.iDisplayStart = this.pageInfo.pageStart - 1
                params.iDisplayLength = this.pageInfo.iDisplayLength
                // params.sortType = '-createDateTime'
                this.listLoading = true
                getClassCountList(params).then(res => {
                    this.created = false
                    const data = res.data
                    this.total = data.iTotalRecords
                    this.listLoading = false
                    this.list.splice(0, this.list.length)
                    let list = data.aaData
                    let over = 0, total = 0
                    for (let i = 0; i < list.length; i++) {
                        const el = list[i]
                        if (i > 0) {
                            const eli = list[i - 1]
                            let piece = 0, totalPiece = 0
                            if (el.portName !== eli.portName || el.pieceTime.substr(0, 10) !== eli.pieceTime.substr(0, 10) || el.groupName !== eli.groupName) {
                                for (let j = over; j < i; j++) {
                                    piece = piece + Number(list[j].piece)
                                }
                                over = i
                                this.list.push({ piece: piece.toFixed(2), portName: '小计' })
                            }
                            this.list.push({ ...el, index: i + 1 })
                            if (i === list.length - 1) {
                                for (let j = over; j < i + 1; j++) {
                                    totalPiece = totalPiece + Number(list[j].piece)
                                }
                                this.list.push({ piece: totalPiece.toFixed(2), portName: '小计' })
                            }
                        } else {
                            this.list.push({ ...el, index: i + 1 })
                        }
                        total = total + Number(list[i].piece)
                    }
                    this.setTotal = total.toFixed(2)
                    // this.list.push({ piece: total, portName: '合计' })
                })
            },
            getSummary(params) {
                const { columns, data } = params
                const sums = [];
                columns.forEach((column, index) => {
                    if (index === 1) {
                        sums[index] = '合计';
                        return;
                    }
                    const values = data.map(item => Number(item[column.property]));
                    if (!values.every(value => isNaN(value)) && column.property === 'piece') {
                        sums[index] = this.setTotal
                        sums[index] += ' ';
                    } else {
                        sums[index] = '';
                    }
                });
                return sums;
            },
            handleExport() {
                let map = new Map();
                map.set("portName", "作业港口")
                map.set("pieceTime", "作业日期")
                map.set("groupName", "作业班组")
                map.set("planType", "作业类型")
                map.set("workShift", "作业班次")
                map.set("containerSize", "箱尺寸")
                map.set("jobNum", "作业量")
                map.set("piece", "工时")
                this.condition.search_IN_portCode = this.arrayToString(this.allPortCodes)
                let params = this.$assist.copySearchConditions(this.condition)
                params.iDisplayStart = this.pageInfo.pageStart - 1
                params.iDisplayLength = 9999
                getClassCountList(params).then(res => {
                    let exportRecords = [];
                    let exportArr = res.data.aaData;
                    exportArr.forEach(record => {
                        let exportRecord = {};
                        for (let [key, value] of map.entries()) {
                            if (key === "planType") {
                                record[key] = allJobStatus.get(record[key]);
                            }
                            exportRecord[value] = record[key];
                        }
                        exportRecords.push(exportRecord);
                    });
                    newExportExcel("作业班组统计", exportRecords);
                })
            },
            arrayToString:function(arr){
                let value = ""
                if (arr != null && arr != "" && arr.length > 0){
                    arr.forEach((column, index) => {
                        value = value + "," + column
                    })
                    value = value.substring(1)
                }
                return value
            },
            handleSee(item) {
                let params = {
                    search_LIKE_className: item.groupName,
                    search_EQ_portCode: item.portCode,
                    search_GTE_jobTime: this.condition['search_GTE_jobTime'],
                    search_LTE_jobTime: this.condition['search_LTE_jobTime'],
                    search_EQ_containerSize: item.containerSize,
                    search_EQ_planType: item.planType,
                    search_LIKE_workShift: item.workShift,
                }
                sessionStorage.setItem('classPerson', JSON.stringify(params))
                sessionStorage.setItem('personId', item.id)
                this.$router.push({ path: '/work/workPerson', name: '作业人员统计' })
            },
            handleChangeEnd(val) {
                let setVal = val;
                if (val) {
                    setVal = val.split(" ")[0] + " 23:59:59";
                }
                this.condition["search_LTE_jobTime"] = setVal;
            },
        },
        computed: {
            startPickerOptions() {
                let endDate = this.condition["search_LTE_jobTime"];
                return {
                    disabledDate(time) {
                        if (endDate) {
                            return time.getTime() > new Date(endDate).getTime();
                        } else {
                            return false;
                        }
                    }
                };
            },
            endPickerOptions() {
                let startDate = this.condition["search_GTE_jobTime"];
                return {
                    disabledDate(time) {
                        if (startDate) {
                            return time.getTime() < new Date(startDate).getTime();
                        } else {
                            return false;
                        }
                    }
                };
            },
        },
        watch: {
            pageInfo: {
                deep: true,
                handler: function () {
                    this.loadData()
                }
            }
        },
        filters: {
            filterDate(val) {
                return val ? val.substr(0, 10) : ''
            }
        }
    }
</script>

<style scoped>

</style>
